package com.t.bricks.bussiness.db.dao.orders.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.t.bricks.bussiness.db.dao.orders.OrdersDao;
import com.t.bricks.bussiness.db.entity.orders.Orders;
import com.t.bricks.bussiness.db.entity.orders.base.OrdersDetailBase;
import com.t.bricks.bussiness.db.mapper.orders.OrdersMapper;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.data.MoneyUtil;
import com.t.bricks.utils.spring.ModuleUtil;

@Repository
public class OrdersDaoImpl implements OrdersDao<Orders> {

	@Autowired
	private OrdersMapper ordersMapper;

	/**
	 * 添加
	 * @Param orders
	 * @return int
	 */
	@Override
	@Transactional
	public MsgEmity addCustom(Orders orders) {
		try {
			int i = ordersMapper.add(orders);
			if (i < 1) {
				Log.error("新增未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "新增数据失败！", 7001);
			}
			
			i = ordersMapper.addDetail(orders.getDetails());
			if (i != orders.getDetails().size()) {
				Log.error("新增明细未能得到预期影响值(预期", orders.getDetails().size(), "):", i);
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "新增数据(新增明细)失败！", 7002);
			}
			
			i = ordersMapper.delCart(orders.getsId());
			if (i != orders.getDetails().size()) {
				Log.error("删除购物车详情记录未能得到预期影响值(预期", orders.getDetails().size(), "):", i);
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "新增数据(删除购物车详情记录)失败！", 7003);
			}
		} catch (Exception e) {
			Log.error("新增时发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
			return new MsgEmity(false, "新增失败！", 7004);
		}
		
		return new MsgEmity(true, "新增成功！", orders);
	}
	
	/**
	 * 查询购物车对应详情
	 * @param cartIds
	 * @param sCustomerId
	 * @return List<OrdersDetailBase>
	 */
	@Override
	public MsgEmity cartToDetail(List<String> cartIds, String sCustomerId) {
		List<OrdersDetailBase> list = null;
		try {
			list = ordersMapper.cartToDetail(cartIds, sCustomerId);
			if (null == list) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
			if (list.size() < 1) {
				return new MsgEmity(true, "查询成功，但没有数据！", list);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}
	
	/**
	 * 设置状态-支付
	 * @param sId
	 * @param sRechargeNo
	 * @param iVersion
	 * @return
	 */
	@Override
	@Transactional
	public MsgEmity pay(String sId, String sRechargeNo, Integer iVersion) {
		try {
			String sCustomerId = ModuleUtil.currentLoginUserId();
			int i = ordersMapper.isAstrictBuy(sId, sCustomerId);
			if (i > 0) {
				return new MsgEmity(false, "操作失败！订单包含已经购买的限购商品", 7001);
			}
			
			ordersMapper.addAstrictBuy(sId, sCustomerId);//新增限购记录(支付时),可能会没有影响数

			i = ordersMapper.pay(sId, sRechargeNo, iVersion);
			if (0 == i) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "操作失败！执行没有影响数,请刷新后重新进行", 7002);
			}
			
			i = ordersMapper.addPayLog(sId);
			if (0 == i) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "操作失败！添加支付流水失败", 7003);
			}
			
			i = ordersMapper.changeStock(sId);
			if (i < 1) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "操作失败！没有影响库存", 7004);
			}
			
			MsgEmity me = this.getValueByFieldName(sId, Arrays.asList("sCustomerId", "mMoneyPay", "mFreight", "iTallyPay"), false);
			if (!me.isSuccess()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return me.appendDataCode(-800);
			}

			Orders orders = me.getData();
			if (MoneyUtil.isPlus(orders.getmMoneyPay())) {//订单使用了余额
				BigDecimal subMoney = orders.getmMoneyPay();
				
				if (MoneyUtil.isPlus(orders.getmFreight())) {//订单有运费
					subMoney = MoneyUtil.sum(subMoney, orders.getmFreight());
				}

				me = ModuleUtil.callServiceMethod("customerAccountServiceImpl", "subFund",
						new Class<?>[] { String.class, BigDecimal.class },
						new Object[] { orders.getsCustomerId(), subMoney });
				if (!me.isSuccess()) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
					return me.appendDataCode(-900);
				}
			} else if (MoneyUtil.isZero(orders.getmMoneyPay()) && MoneyUtil.isPlus(orders.getmFreight())) {//订单无余额但有运费
				me = ModuleUtil.callServiceMethod("customerAccountServiceImpl", "subFund",
						new Class<?>[] { String.class, BigDecimal.class },
						new Object[] { orders.getsCustomerId(), orders.getmFreight() });
				if (!me.isSuccess()) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
					return me.appendDataCode(-900);
				}
			}

			if (null != orders.getiTallyPay() && 0 < orders.getiTallyPay().intValue()) {//订单使用积分
				me = ModuleUtil.callServiceMethod("customerAccountServiceImpl", "subTally",
						new Class<?>[] { String.class, Integer.class },
						new Object[] { orders.getsCustomerId(), orders.getiTallyPay() });
				if (!me.isSuccess()) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
					return me.appendDataCode(-900);
				}
			}

			return new MsgEmity(true, "操作成功！状态已经变为'已支付'", i);
		} catch (Exception e) {
			Log.error("设置状态-销售发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
			return new MsgEmity(false, "操作失败，请查看异常日志", 7005);
		}
	}
	
	/**
	 * 设置状态-销售
	 * @param sId
	 * @param iVersion
	 * @param sSalesmanId
	 * @param sSalesman
	 * @return
	 */
	@Override
	public MsgEmity sales(String sId, Integer iVersion, String sSalesmanId, String sSalesman) {
		try {
			int i = ordersMapper.sales(sId, iVersion, sSalesmanId, sSalesman);
			if (0 == i) {
				return new MsgEmity(false, "操作失败！请刷新后重新进行", 7001);
			}
			
			return new MsgEmity(true, "操作成功！状态已经变为'销售'", i);
		} catch (Exception e) {
			Log.error("设置状态-销售发生异常:", e.getMessage());
			return new MsgEmity(false, "操作失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 设置状态-送出(待揽货)
	 * @param sId
	 * @param iVersion
	 * @param dDelivery
	 * @param sDelivery
	 * @param sDeliveryman
	 * @param sDeliveryNo
	 * @param sDelveryCode
	 * @return
	 */
	@Override
	public MsgEmity delivery(String sId, Integer iVersion, Date dDelivery,
			String sDelivery, String sDeliveryman, String sDeliveryNo,
			String sDelveryCode) {
		try {
			int i = ordersMapper.delivery(sId, iVersion, dDelivery, sDelivery,
					sDeliveryman, sDeliveryNo, sDelveryCode);
			if (0 == i) {
				return new MsgEmity(false, "操作失败！请刷新后重新进行", 7001);
			}
			
			return new MsgEmity(true, "操作成功！状态已经变为'送货'", i);
		} catch (Exception e) {
			Log.error("设置状态-送货发生异常:", e.getMessage());
			return new MsgEmity(false, "操作失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 顾客签收
	 * @param sId
	 * @param iVersion
	 * @param sSignIn
	 * @return
	 */
	@Override
	public MsgEmity signIn(String sId, Integer iVersion, String sSignIn) {
		try {
			int i = ordersMapper.signIn(sId, iVersion, sSignIn);
			if (i < 1) {
				Integer k = this.getiVersion(sId);//如果更新操作的影响数小于1,则检查数据是否存在
				if (null == k) {
					return new MsgEmity(false, "'顾客签收'操作失败，数据可能已经被删除！", 7001);// 无法获取版本号,说明数据已经不存在
				}
				
				if (!iVersion.equals(k)) {
					return new MsgEmity(false, "'顾客签收'操作失败，系统中的数据可能已经被更新！", 7002);
				}
				
				k = this.getiState(sId);
				if (k.intValue() > 4 || k.intValue() < 4) {
					return new MsgEmity(false, "'顾客签收'操作失败，记录状态值不符合要求！", 7003);
				}

				Log.error("'顾客签收'操作得到预期影响值(预期:1):", i);
				return new MsgEmity(false, "'顾客签收'操作失败！", 7004);
			}
			
			return new MsgEmity(true, "'顾客签收'操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("'顾客签收'操作发生异常:", e.getMessage());
			return new MsgEmity(false, "'顾客签收'操作失败，请查看异常日志", 7005);
		}
	}
	
	/**
	 * 顾客确认
	 * @param sId
	 * @param iVersion
	 * @param sConfirm
	 * @return
	 */
	@Override
	public MsgEmity confirm(String sId, Integer iVersion, String sConfirm) {
		try {
			int i = ordersMapper.confirm(sId, iVersion, sConfirm);
			if (i < 1) {
				Integer k = this.getiVersion(sId);//如果更新操作的影响数小于1,则检查数据是否存在
				if (null == k) {
					return new MsgEmity(false, "'顾客确认'操作失败，数据可能已经被删除！", 7001);// 无法获取版本号,说明数据已经不存在
				}
				
				if (!iVersion.equals(k)) {
					return new MsgEmity(false, "'顾客确认'操作失败，系统中的数据可能已经被更新！", 7002);
				}
				
				k = this.getiState(sId);
				if (k.intValue() > 5 || k.intValue() < 4) {
					return new MsgEmity(false, "'顾客确认'操作失败，记录状态值不符合要求！", 7003);
				}

				Log.error("'顾客确认'操作得到预期影响值(预期:1):", i);
				return new MsgEmity(false, "顾客签收失败！", 7004);
			}
			
			return new MsgEmity(true, "'顾客确认'操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("'顾客确认'操作发生异常:", e.getMessage());
			return new MsgEmity(false, "'顾客确认'操作失败，请查看异常日志", 7005);
		}
	}
	
	/**
	 * 顾客退货申请
	 * @param sId
	 * @param iVersion
	 * @param sReturnApply 退货申请说明
	 * @return
	 */
	@Override
	@Transactional
	public MsgEmity returnApply(String sId, Integer iVersion, String sReturnApply) {
		try {
			int i = ordersMapper.returnApply(sId, iVersion, sReturnApply);
			if (i < 1) {
				Integer k = this.getiVersion(sId);//如果更新操作的影响数小于1,则检查数据是否存在
				if (null == k) {
					return new MsgEmity(false, "'顾客退货申请'操作失败，数据可能已经被删除！", 7001);// 无法获取版本号,说明数据已经不存在
				}
				
				if (!iVersion.equals(k)) {
					return new MsgEmity(false, "'顾客退货申请'操作失败，系统中的数据可能已经被更新！", 7002);
				}
				
				k = this.getiState(sId);
				if (k.intValue() > 5 || k.intValue() < 2) {
					return new MsgEmity(false, "'顾客退货申请'操作失败，记录状态值不符合要求！", 7003);
				}

				Log.error("'顾客退货申请'操作得到预期影响值(预期:1):", i);
				return new MsgEmity(false, "顾客签收失败！", 7004);
			}
			
			i = ordersMapper.addRetrun(sId);
			if (i < 1) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "创建退单记录失败！", 7005);
			}
			
			return new MsgEmity(true, "操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("顾客操作状态值发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
			return new MsgEmity(false, "操作失败，请查看异常日志", 7006);
		}
	}
	
	/**
	 * 设置状态-退货审核
	 * 8:退货审核不通过;9:退货申请通过;10:已退款
	 * @param sId
	 * @param iVersion
	 * @param iState
	 * @return
	 */
	@Override
	public MsgEmity untreadAudit(String sId, Integer iVersion, Integer iState) {
		try {
			int i = ordersMapper.untreadAudit(sId, iVersion, iState);
			if (0 == i) {
				return new MsgEmity(false, "操作失败！请刷新后重新进行", 7001);
			}
			
			return new MsgEmity(true, "操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("设置状态-退货审核发生异常:", e.getMessage());
			return new MsgEmity(false, "操作失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 设置状态-审核
	 * @param sId
	 * @param iVersion
	 * @param sAuditId
	 * @param sAudit
	 * @return
	 */
	@Override
	public MsgEmity audit(String sId, Integer iVersion, String sAuditId, String sAudit) {
		try {
			int i = ordersMapper.audit(sId, iVersion, sAuditId, sAudit);
			if (0 == i) {
				return new MsgEmity(false, "操作失败！请刷新后重新进行", 7001);
			}
			
			return new MsgEmity(true, "操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("设置状态-审核发生异常:", e.getMessage());
			return new MsgEmity(false, "操作失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 设置状态-复审
	 * @param sId
	 * @param iVersion
	 * @param sRecheckId
	 * @param sRecheck
	 * @return
	 */
	@Override
	public MsgEmity recheck(String sId, Integer iVersion, String sRecheckId, String sRecheck) {
		try {
			int i = ordersMapper.recheck(sId, iVersion, sRecheckId, sRecheck);
			if (0 == i) {
				return new MsgEmity(false, "操作失败！请刷新后重新进行", 7001);
			}
			
			return new MsgEmity(true, "操作成功！状态已经改变", i);
		} catch (Exception e) {
			Log.error("设置状态-复审发生异常:", e.getMessage());
			return new MsgEmity(false, "操作失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 测算商品运费
	 * @param details 订单详情集合
	 * @param sArea 目的地
	 * @return
	 */
	@Override
	public MsgEmity reckonFreight(List<OrdersDetailBase> details, String sArea) {
		try {
			BigDecimal money = ordersMapper.reckonFreight(details, sArea);
			if (null == money) {
				return new MsgEmity(false, "测算商品运费失败！", 7001);
			}
			
			return new MsgEmity(true, "测算商品运费成功", money);
		} catch (Exception e) {
			Log.error("测算商品运费发生异常:", e.getMessage());
			return new MsgEmity(false, "测算商品运费失败，请查看异常日志", 7002);
		}
	}
	
	/**
	 * 顾客订单中是否包含已经购买过的限购商品
	 * @Param sOrderId 订单编号
	 * @Param sCustomerId 顾客编号
	 * @return
	 */
	@Override
	public MsgEmity isAstrictBuy(String sOrderId, String sCustomerId) {
		try {
			int i = ordersMapper.isAstrictBuy(sOrderId, ModuleUtil.currentLoginUserId());
			if (i > 0) {
				return new MsgEmity(false, "操作失败！订单包含已经购买的限购商品", 7001);
			}

			return new MsgEmity(true, "商品没有被限购", i);
		} catch (Exception e) {
			Log.error("测算商品运费发生异常:", e.getMessage());
			return new MsgEmity(false, "测算商品运费失败，请查看异常日志", 7002);
		}
	}
	
}
